from django.http import HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.urls import reverse, reverse_lazy
from tasks.forms import AddTaskForm, ChangeTaskForm, TaskDoneForm
from .models import Tasks
from users.models import User
from datetime import datetime
from django.contrib.messages.views import SuccessMessageMixin
from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import UpdateView
from django.utils import timezone
from tasks.services import check_tasks_creation_time, create_empty_tasks


@login_required
def main(request, year=None):
    if year is None:
        year = str(datetime.now().year)

    tasks = Tasks.objects.filter(owner=request.user).filter(year=year)
    count = tasks.count()
    ready = tasks.filter(is_done=True).count()
    rewards = tasks.filter(reward__isnull=False)
    add_8_tasks_if_all_done = count == ready
    context = {'count': count,
               'tasks': tasks,
               'ready': ready,
               'all_done': add_8_tasks_if_all_done,
               'rewards': rewards,
               'actual_year': str(datetime.now().year), # actual year anytime
               'year': year
               }
    return render(request, 'users/profile.html', context)


@login_required
def add_task(request, task_id):
    
    if request.method in ['POST', 'FILES']:
        form = AddTaskForm(request.POST, request.FILES)
        owner = request.user.username
        user = User.objects.get(username=owner)
        task = Tasks.objects.get(owner=user, id=task_id)

        if form.is_valid():

            title = request.POST['title']
            description = request.POST['description']
            start_img = request.FILES.get('start_img')
            remind = request.POST['remind_by_date']
            task.title = title
            task.description = description
            if remind:
                task.remind_by_date = remind  # YYYY-mm-dd
            task.start_img = start_img
            task.status = 'AC'
            task.creation_date = timezone.now()
            task.save()
        return HttpResponseRedirect(reverse('task:main'))
    else:
        form = AddTaskForm()

    year = str(datetime.now().year)

    context = {
        'form': form,
        'year': year
    }
    return render(request, 'tasks/add_task.html', context)


@login_required
def task_detail(request, task_id):

    task = Tasks.objects.filter(owner=request.user).filter(id=task_id)
    year = str(datetime.now().year)

    context = {
        'task': task,
        'year': year}
    return render(request, 'tasks/one_task_detail.html', context)


class TaskChangeView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
    """ Update task """
    model = Tasks
    template_name = 'tasks/task-change.html'
    form_class = ChangeTaskForm
    success_url = reverse_lazy('task:main')

    def setup(self, request, *args, **kwargs):
        self.user_id = request.user.pk
        self.task_id = kwargs['task_id']
        return super().setup(request, *args, **kwargs)

    def get_object(self, queryset=None):
        if not queryset:
            queryset = self.get_queryset()
        task = get_object_or_404(queryset, pk=self.task_id)
        self.done = task.is_done
        self.creation_date = task.creation_date
        return get_object_or_404(queryset, pk=self.task_id)
    
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['done'] = self.done
        context['task_id'] = self.task_id
        context['creation_date'] = self.creation_date
        return context


class TaskDoneView(LoginRequiredMixin, UpdateView):
    """ Update task """
    model = Tasks
    template_name = 'tasks/task-done.html'
    form_class = TaskDoneForm
    success_url = reverse_lazy('task:main')

    def setup(self, request, *args, **kwargs):
        self.user_id = request.user.pk
        self.task_id = kwargs['task_id']
        return super().setup(request, *args, **kwargs)

    def get_object(self, queryset=None):
        if not queryset:
            queryset = self.get_queryset()
            
        return get_object_or_404(queryset, pk=self.task_id)

    def form_valid(self, form):
        instance = form.save(commit=False)
        instance.is_done = True
        instance.ended_date = datetime.now().strftime("%Y-%m-%d")
        instance.save()
        return super().form_valid(form)


def error_404(request, exception):
    response = render(request, 'errors/404.html')
    response.status_code = 404
    return response


@login_required
def add_empty_tasks(request, year=None, name=None, count=None):
    if name is None:
        name = request.user
    if year is None:
        year = datetime.now().year
    if count is None:
        count = 40

    task_owner = User.objects.get(email=name)
    all_tasks = Tasks.objects.filter(owner=task_owner).filter(year=year)
    tasks_count = all_tasks.count()
    latest_task_created = False
    if tasks_count == 0:
        create_empty_tasks(year, count, task_owner)
    else:
        latest_task_created = all_tasks.order_by('id').last().creation_date
    
    if tasks_count and count < 40:
        if check_tasks_creation_time(latest_task_created):
            create_empty_tasks(year, count, task_owner)
    
    tasks = Tasks.objects.filter(owner=task_owner).filter(year=year)
    count = tasks.count()
    ready = tasks.filter(is_done=True).count()
    rewards = tasks.filter(reward__isnull=False)

    context = {'count': count,
               'tasks': tasks,
               'ready': ready,
               'rewards': rewards,
               'actual_year': str(datetime.now().year),
               'year': str(datetime.now().year)  # actual year anytime
               }
    return render(request, 'users/profile.html', context)